<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Card, Form, Input, Button, Space, message } from 'ant-design-vue'
import { studentTaskApi } from '@/api/modules/studentTask'
import type { StudentTaskVO, TaskSubmissionDTO } from '@/types/task'
import dayjs from 'dayjs'
import { useRoute, useRouter } from 'vue-router'
import FileUpload from '@/components/business/FileUpload.vue'
import { SubmissionStatus } from '@/types/task'

const route = useRoute()
const router = useRouter()
const taskId = Number(route.params.id)

// 任务详情
const loading = ref(false)
const taskDetail = ref<StudentTaskVO>()

// 表单
const formRef = ref()
const formState = ref<{
  files: Array<{ fileName: string; fileUrl: string; fileSize: number; fileType: string }>;
  comment: string;
}>({
  files: [],
  comment: ''
})

// 表单校验规则
const rules = {
  files: [
    { required: true, message: '请上传文件' }
  ]
}

// 状态标签配置
const statusTagConfig = {
  [SubmissionStatus.PENDING]: { color: 'warning', text: '待审核' },
  [SubmissionStatus.TEACHER_REVIEWING]: { color: 'processing', text: '教师审核中' },
  [SubmissionStatus.APPROVED]: { color: 'success', text: '已通过' },
  [SubmissionStatus.REJECTED]: { color: 'error', text: '已驳回' }
}

// 获取任务详情
const fetchTaskDetail = async () => {
  loading.value = true
  try {
    const data = await studentTaskApi.getTaskDetail(taskId)
    taskDetail.value = data

    // 获取提交详情
    if (data.submissionId) {
      const submissionDetail = await studentTaskApi.getSubmissionDetail(data.submissionId)
      console.log(submissionDetail)
      formState.value = {
        files: submissionDetail.files.map(file => ({
          fileName: file.fileName,
          fileUrl: file.fileUrl,
          fileSize: file.fileSize,
          fileType: file.fileType
        })),
        comment: submissionDetail.comment || ''
      }
    }
    console.log('formState.value', formState.value);
    
  } catch (error) {
    console.error('获取任务详情失败:', error)
    message.error(error||'获取任务详情失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    console.log(formState.value)
    await formRef.value.validate()
    
    const submitData: TaskSubmissionDTO = {
      taskId,
      files: formState.value.files,
      comment: formState.value.comment
    }

    if (taskDetail.value?.submitted) {
      // 修改提交
      await studentTaskApi.updateSubmission(taskId, submitData)
      message.success('修改成功')
    } else {
      // 新提交
      await studentTaskApi.submit(taskId, submitData)
      message.success('提交成功')
    }

    // 返回详情页
    router.push(`/student/task/detail/${taskId}`)
  } catch (error) {
    console.error('提交失败:', error)
    message.error(error || '提交失败')
  }

}

// 返回详情页
const handleBack = () => {
  router.push(`/student/task/detail/${taskId}`)
}

onMounted(() => {
  fetchTaskDetail()
})
</script>

<template>
  <div class="task-submit">
    <Card :loading="loading">
      <template #title>{{ taskDetail?.submitted ? '修改提交' : '提交任务' }}</template>

      <!-- 任务信息 -->
      <div class="task-info">
        <h3>{{ taskDetail?.name }}</h3>
        <p class="deadline">
          截止时间: {{ taskDetail?.deadline ? dayjs(taskDetail.deadline).format('YYYY-MM-DD HH:mm:ss') : '-' }}
        </p>
        <div class="requirements" v-if="taskDetail?.fileRequirements">
          <h4>文件要求</h4>
          <p>{{ taskDetail.fileRequirements }}</p>
        </div>
        <div class="requirements" v-if="taskDetail?.submitRequirements">
          <h4>提交要求</h4>
          <p>{{ taskDetail.submitRequirements }}</p>
        </div>
      </div>

      <!-- 提交表单 -->
      <Form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 16 }"
      >
        <Form.Item
          label="上传文件"
          name="files"
          :rules="rules.files"
        >
          <FileUpload v-model:value="formState.files" />
        </Form.Item>

        <Form.Item
          label="提交说明"
          name="comment"
        >
          <Input.TextArea
            v-model:value="formState.comment"
            placeholder="请输入提交说明"
            :rows="4"
            :maxlength="200"
            show-count
          />
        </Form.Item>

        <Form.Item :wrapper-col="{ offset: 1 }">
          <Space>
            <Button type="primary" @click="handleSubmit">
              {{ taskDetail?.submitted ? '修改' : '提交' }}
            </Button>
            <Button @click="handleBack">返回</Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  </div>
</template>

<style lang="less" scoped>
.task-submit {
  .task-info {
    margin-bottom: 24px;
    padding: 16px;
    background-color: #fafafa;
    border-radius: 2px;

    h3 {
      margin: 0 0 8px;
      color: rgba(0, 0, 0, 0.85);
    }

    .deadline {
      margin: 0 0 16px;
      color: #ff4d4f;
    }

    .requirements {
      margin-top: 16px;

      h4 {
        margin: 0 0 8px;
        color: rgba(0, 0, 0, 0.85);
      }

      p {
        margin: 0;
        color: rgba(0, 0, 0, 0.65);
        white-space: pre-wrap;
      }
    }
  }
}
</style> 
